import { UserWhereProps } from './types'
import { RegisterModel, UserModelProps } from '../db/models/user'
import { createMD5 } from '../utils/createMD5'
import { UserModel } from '../db/models'

export const createUser = async ({ username, password, email, mobile, status }: RegisterModel) => {
  const result = await UserModel.create({
    username,
    password,
    email,
    mobile,
    status
  })
  return result.toJSON()
}

/**
 * @author lihh
 * @description 用来获取用户信息
 * @param username 表示用户名称
 * @param password 表示用户密码
 * @param id 用户主键id
 */
export const getUserInfo = async ({ username, password, id }: UserWhereProps): Promise<UserModelProps | null> => {
  const where: UserWhereProps = { username }
  if ( password ) where.password = createMD5(password)
  if ( typeof id !== 'undefined' ) where.id = id

  const result = await UserModel.findOne({
    attributes: {
      exclude: [ 'password', 'createdAt', 'updatedAt' ]
    },
    where
  })
  if ( result === null ) return null
  return result.toJSON() as UserModelProps
}
